package com.intrasoft.nelsonalva.intrasms;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

public class LANConnector {

    public int executeQuery(String url, String query) throws SQLException, ClassNotFoundException, IOException, FileNotFoundException, InvalidFormatException {

        String rutabd = "jdbc:postgresql://" + url + "/sender_bd_v.1.2"; /*o localhost:puerto*/
        String user = "smssender", pwd = "smssender";

        Class.forName("org.postgresql.Driver");
        DriverManager.setLoginTimeout(5);
        Connection connection = null;

        try {
            connection = DriverManager.getConnection(rutabd, user, pwd);
        } catch (SQLException ex) {/*ex.printStackTrace();*/
            System.out.println("ERROR revisar conexion");
            SCQuery scquery = new SCQuery();
            try {
                scquery.bufferStrings();
            } catch (SQLException ex1) {
            }
        }

        Statement statement = connection.createStatement();

        int rows = statement.executeUpdate(query); /*Nótese que el tipo 'int rows' se incluye para 
         poder generar un conteo al ejecutar la orden*/

        statement.close();
        connection.close();

        return rows;

    }

    public void executeSelect(String url, String query, String sc) throws SQLException, ClassNotFoundException, IOException, FileNotFoundException, InvalidFormatException {

        SCQuery scquery = new SCQuery();
        String rutabd = "jdbc:postgresql://" + url + "/sender_bd_v.1.2"; /*o localhost:puerto*/
        String user = "smssender", pwd = "smssender";

        Class.forName("org.postgresql.Driver");
        DriverManager.setLoginTimeout(5);
        Connection connection = null;

        try {
            connection = DriverManager.getConnection(rutabd, user, pwd);
        } catch (SQLException ex) {/*ex.printStackTrace();*/
            System.out.println("ERROR revisar conexion");
            try {
                scquery.bufferStrings();
            } catch (SQLException ex1) {
            }
        }

        Statement statement = connection.createStatement();

        ResultSet resultset = statement.executeQuery(query);

        SelectQuery sq = new SelectQuery();

        sq.writeExcel(resultset, sc);

        resultset.close();
        statement.close();
        connection.close();
    }
}